var apiHost = wx.getStorageSync("apiHost");
var Appid = wx.getStorageSync("Appid");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    indexHeght:'',
    addresList:[],          //收货地址信息
    sendType : '',          //收获方式
    radioFlag : false,      //单点框判断
    addressId :'',          //收货地址id
    selfAddressId:'',       //自提点id
    leaveMsg:'',            //留言值
    skuIds: '',              //规格id拼接 例如:a:b:c
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.indexHeght();                        //支付详情页

    var userId = wx.getStorageSync("userId");
    var sendResStr = options.sendResStr;      //详情页传递参数

    // 判断是否有传递的参数(防止选择收货地址回来丢失)
    if (sendResStr != undefined){
      wx.setStorageSync("sendResStr", sendResStr);
    }else{
      sendResStr = wx.getStorageSync("sendResStr");
    }
    sendResStr = JSON.parse(sendResStr);      

    var collageId = sendResStr.collageId; //拼团id
    var count = sendResStr.shopNum;       //购买数量
    var skuIdsStr = sendResStr.skuIdsStr; //规格id拼接

    // 规格集合
    that.setData({
      userId: userId,
      collageId: collageId,
      count: count,
      skuIds: skuIdsStr
    });

    that.initPayment(collageId, userId, count)

    // 选择收货地址
    var addresList = options.addresList;
    if (addresList!=undefined){
      var addresListJson = JSON.parse(addresList); //字符串 转 json
      var addressId = addresListJson.addressId;

      var name = addresListJson.name;
      var region = addresListJson.region;
      var address = addresListJson.address;
      var phone = addresListJson.phone;

      that.setData({
        addresList: addresListJson,
        addressId:addressId,
        name: name,
        phone: phone
      });
      that.initPriceDetai(collageId, addressId, count)
    }

    // 自提点 
    var setOneselfRaiseDot = options.setOneselfRaiseDot;
    if (setOneselfRaiseDot != undefined) {
      var setOneselfRaiseDotJson = JSON.parse(setOneselfRaiseDot); //字符串 转 json

      var addressId = setOneselfRaiseDotJson.id;
      var name = setOneselfRaiseDotJson.name;
      var region = setOneselfRaiseDotJson.region;
      var address = setOneselfRaiseDotJson.address;
      var phone = setOneselfRaiseDotJson.phone;

      that.setData({
        addresList: setOneselfRaiseDotJson,
        addressId: addressId,
        selfAddressId: addressId,
        name: name,
        phone: phone
      });
      that.initPriceDetai(collageId, addressId, count)
    }
    
  },

  /**
   * 初始化 支付详情页 （获取收货地址）
   */
  initPayment: function (collageId,userId, count){
    var that = this;
    wx.showLoading({
      title: '玩命加载中',
      icon: "loading",
      mask: true
    })
    wx.request({
      url: apiHost + 'hpp/pay/detail',
      method: 'GET',
      header: {
        "contenr-type": "application/json"
      },
      data: {
        collageId: collageId,
        userId: userId,
        count: count
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        console.log(res)
        if (code == "10000") {
          var sendType = res.data.data.sendType;   //收获方式
          var fee = res.data.data.fee;             //运费
          var actualPay = res.data.data.actualPay; //实际付款
          var payType = res.data.data.payType;     //支付方式
          that.setData({
            sendType: sendType,
            fee: fee,
            actualPay: actualPay,
            payType: payType
          })
          wx.hideLoading();
        } else {
          wx.hideLoading();
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
      fail: function () {
        wx.hideLoading();
        wx.showToast({
          title: "网络异常",
          icon: 'none',
          duration: 2000,
          mask: true
        });
      }
    })
  },

  /**
   * 计算实付款以及运费
   */
  initPriceDetai: function (collageId, addressId, count){
    var that = this;
    wx.showLoading({
      title: '玩命加载中',
      icon: "loading",
      mask: true
    })
    wx.request({
      url: apiHost + 'hpp/pay/calActualPay',
      method: 'GET',
      header: {
        "contenr-type": "application/json"
      },
      data: {
        collageId: collageId,
        addressId: addressId,
        count: count
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          var fee = res.data.data.fee;             //运费
          var actualPay = res.data.data.actualPay; //实际付款
          that.setData({
            fee: fee,
            actualPay: actualPay
          })
          wx.hideLoading();
        } else {
          wx.hideLoading();
          wx.showToast({
            title: msg ,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
      fail: function () {
        wx.hideLoading();
        wx.showToast({
          title: "网络异常",
          icon: 'none',
          duration: 2000,
          mask: true
        });
      }
    })
  },

  /**
   * 选择收货地址
   */
  selectAddList: function () {
    wx.showLoading({
      title: '跳转中',
      icon: 'loading',
      mask: true
    });
    wx.redirectTo({
      url: '../../../personal/personAddress/personAddressList/personAddressList?flag=' + 1,
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },

  /**
   * 选择自提点
   */
  selectsetOneselfRaiseDot:function(){
    wx.showLoading({
      title: '跳转中',
      icon: 'loading',
      mask: true
    });
    wx.redirectTo({
      url: '../../../personal/setOneselfRaiseDot/selectSetOneselfRaiseDot/selectSetOneselfRaiseDot?',
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },

  /**
   * 是否信任团长
   */
  radioChange:function(){
    var that= this;

    var radioFlag = that.data.radioFlag;
    if (radioFlag){
      radioFlag = false;
    }else{
      radioFlag = true;
    }

    that.setData({
      radioFlag: radioFlag
    });
  },
  /**
   * 获取留言输入框的值
   */
  leaveMsgVal:function(e){
    var that = this;
    var leaveMsg = e.detail.value;
    that.setData({
      leaveMsg: leaveMsg
    });
  },

  /**
   * 立即支付
   */
  nowPay:function(){
    var that = this;
    var payType = that.data.payType;            //支付方式
    var radioFlag = that.data.radioFlag;        //是否信任

    var collageId = that.data.collageId;        //拼团id
    var userId = that.data.userId;              //userId
    var addressId = that.data.addressId;        //收货地址Id

    var actualPay = that.data.actualPay;        //实际付款
    var fee = that.data.fee;                    //运费

    var leaveMsg = that.data.leaveMsg;          //留言
    var selfAddressId = that.data.selfAddressId;//自提点id

    var name = that.data.name;                  //收货人名称
    var phone = that.data.phone;                //收货人手机号
    var skuIds = that.data.skuIds;              //规格id拼接 例如:a:b:c
    var count = that.data.count;                //数量
    var isBelive = that.data.radioFlag;         //是否信任该团长
    var sendType = that.data.sendType;          //发货方式

    // console.log(collageId)
    // console.log(userId)
    // console.log(addressId)
    // console.log(actualPay)
    // console.log(fee)
    // console.log(leaveMsg)
    // console.log(selfAddressId)
    // console.log(name)
    // console.log(phone)
    // console.log(skuIds)
    // console.log(count)
    // console.log(isBelive)
    // console.log(sendType)


    // 判断收货地址
    if (sendType == 'delivery'){
      if (addressId==''){
        that.showMsg("请选择收货地址");
        return
      }
    }

    // 判断自提点
    if (sendType == 'self') {
      if (selfAddressId == '') {
        that.showMsg("请选择自提点");
        return
      }
    }

    // 通过支付方式，判断是否信任团长
    if (payType =='direct'){
      if (!radioFlag){
        that.showMsg("请信任该团长");
        return
      }
    }
    //订单提交
    that.orderSubmit(collageId, userId, addressId, actualPay, fee, leaveMsg, selfAddressId, name, phone, skuIds, count)
  },

  /**
   * 订单提交
   */
  orderSubmit: function (collageId, userId, addressId, actualPay, fee, leaveMsg, selfAddressId, name, phone, skuIds, count){
    var that = this;
    wx.showLoading({
      title: '玩命加载中',
      icon: "loading",
      mask: true
    })
    wx.request({
      url: apiHost + 'hpp/order/submit',
      method: 'POST',
      header: {
        "contenr-type": "application/json"
      },
      data: {
        collageId: collageId,
        userId: userId,
        addressId: addressId,
        actualPay: actualPay,
        fee: fee,
        leaveMsg: leaveMsg,
        selfAddressId: selfAddressId,
        name: name,
        phone: phone,
        skuIds: skuIds,
        count: count,
        isBelive:1
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          
          var appId = res.data.data.appId
          var nonceStr = res.data.data.nonceStr
          var orderNo = res.data.data.orderNo;
          var packages = res.data.data.package
          var paySign = res.data.data.paySign
          var signType = res.data.data.signType
          var timeStamp = res.data.data.timeStamp

          //调支付接口
          wx.requestPayment({
            appId: Appid,
            timeStamp: timeStamp,
            nonceStr: nonceStr,
            'package': packages,
            signType: signType,
            paySign: paySign,
            'success': function (res) {
              //下单成功后跳转到订单详情页
              wx.reLaunch({
                url: '/pages/orders/orderDetail/orderDetail?orderNo=' + orderNo,
              })
            },
            'fail': function (res) {
            }
          })

          wx.hideLoading();
        } else {
          wx.hideLoading();
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
      fail: function () {
        wx.hideLoading();
        wx.showToast({
          title: "网络异常",
          icon: 'none',
          duration: 2000,
          mask: true
        });
      }
    })
  },

  //获取高度
  indexHeght: function () {
    var that = this;
    /*获取指定元素高度*/
    var query3 = wx.createSelectorQuery();
    var indexHeght = "";

    query3.select('#payMentBottomCon').boundingClientRect()
    query3.exec(function (res) {
      indexHeght = res[0].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            indexHeght: res.windowHeight - indexHeght
          });
        }
      });
    });
  },
  /**
   * 提示信息
   */
  showMsg: function (msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000,
      mask: true
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  }
})